// components/organisms/TopIconsPrivate.js
import React, { useRef, useState, useEffect, forwardRef } from 'react';
import { useNavigate, Link as RouterLink, useLocation } from 'react-router-dom';
import { createPortal } from 'react-dom';
import { 
  Box, 
  Typography,
  Toolbar, 
  IconButton, 
  Menu, 
  MenuItem, 
  useMediaQuery, 
  useTheme,
  Link
} from '@mui/material';
import { alpha } from '@mui/material/styles';
import DragHandleIcon from '@mui/icons-material/DragHandle';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import HomeIcon from '@mui/icons-material/Home';
import RefreshIcon from '@mui/icons-material/Refresh';
import { motion } from 'framer-motion';
import { useDarkMode } from 'contexts/DarkMode';
import { useDrawer } from 'contexts/DrawerContext';
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "react-query";
import { useForm } from "react-hook-form";
import { Logout, UpdateMe, Clear } from "api/mutations";
import { useAuth } from "contexts/AuthContext";
import {
  StyledAppBar,
  StyledToolbar,
  ModernButton,
  StyledTypography,
  LogoWrapper,
  FixedLogoText,
  secondToolbarSx,
  dragHandleIconButtonSx,
  dragHandleIconSx,
  homeIconSx,
  homeIconButtonSx,
  languageButtonSx,
  modernButtonSx,
  homeButtonSx,
  accountButtonSx,
  featurePillSx,
  featurePillTypographySx,
  menuPaperSx,
  menuItemSx,
  disabledMenuItemSx,
  fixedLogoContainerSx,
  logoLinkStyle,
  logoTextContainerSx,
  logoTextSx,
  portalButtonSx,
  portalDragIconSx
} from './TopIconsPrivate.styles';

// LogoComponent - moved inside as a constant
const LogoComponent = ({
  darkMode = true,
  isHomePage,
  navigateOpen,
  logoText = 'startersaas.pro',
  linkTo = '/',
  showPlayIcon = true,
  isFixed = false,
}) => {
  const location = useLocation();
  const isHomePageRoute = location.pathname === '/home-page';
  
  // Calculate primary color's RGB value
  const calculatePrimaryRgb = (primaryMainColor) => {
    if (primaryMainColor.startsWith('#')) {
      const r = parseInt(primaryMainColor.slice(1, 3), 16);
      const g = parseInt(primaryMainColor.slice(3, 5), 16);
      const b = parseInt(primaryMainColor.slice(5, 7), 16);
      return `${r}, ${g}, ${b}`;
    }
    return '25, 118, 210';
  };

  // Breakpoints
  const isXs = useMediaQuery('(max-width: 599px)');
  const isSm = useMediaQuery('(min-width: 600px) and (max-width: 959px)');
  const isMd = useMediaQuery('(min-width: 960px) and (max-width: 1279px)');
  const isLg = useMediaQuery('(min-width: 1280px) and (max-width: 1919px)');
  const isXl = useMediaQuery('(min-width: 1920px)');

  // Responsive font size determination with 1.5x sizing
  const getFontSize = () => {
    if (isXs) return 'calc(4.5vh + 1.5vw)';
    if (isSm) return 'calc(7.5vh + 1.5vw)';
    if (isMd) return 'calc(8.25vh + 1.5vw)';
    if (isLg) return 'calc(9vh + 1.5vw)';
    if (isXl) return 'calc(9.75vh + 1.5vw)';
    return '6rem';
  };

  // Responsive icon size determination with 1.5x sizing
  const getIconSize = () => {
    if (isXs) return '3rem';
    if (isSm) return '4.05rem';
    if (isMd) return '4.5rem';
    if (isLg) return '4.8rem';
    if (isXl) return '5.25rem';
    return '4.5rem';
  };

  const fontSize = getFontSize();
  const iconSize = getIconSize();

  // Animation variants for fixed logo
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.15,
        when: "beforeChildren"
      }
    }
  };

  const itemVariants = {
    hidden: { x: -50, opacity: 0 },
    visible: { 
      x: 0, 
      opacity: 1,
      transition: { 
        type: "spring",
        stiffness: 200,
        damping: 20
      }
    }
  };

  // Set CSS variable for primary color
  React.useEffect(() => {
    document.documentElement.style.setProperty(
      '--primary-main-rgb',
      calculatePrimaryRgb('#40d47e')
    );
    
    // Dynamically load the Monoton font if not already present
    const monotonFont = document.createElement('link');
    monotonFont.rel = 'stylesheet';
    monotonFont.href = 'https://fonts.googleapis.com/css2?family=Monoton&display=swap';
    document.head.appendChild(monotonFont);
    
    return () => {
      document.head.removeChild(monotonFont);
    };
  }, []);

  // Render the fixed logo when isFixed is true
  if (isFixed) {
    return (
      <Box 
        component={motion.div}
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        sx={fixedLogoContainerSx(darkMode)}
      >
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          Starter
        </FixedLogoText>
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          Saas
        </FixedLogoText>
        <FixedLogoText variants={itemVariants} darkMode={darkMode} isHomePage={isHomePageRoute}>
          .pro
        </FixedLogoText>
      </Box>
    );
  }

  // Render the original logo when not fixed
  return (
    <LogoWrapper className="logo-component">
      <Link
        to={linkTo}
        style={logoLinkStyle}
      >
        <Box sx={logoTextContainerSx}>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            Starter
          </StyledTypography>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            Saas
          </StyledTypography>
          <StyledTypography fontSize={fontSize} darkMode={darkMode} isHomePage={isHomePageRoute} sx={logoTextSx}>
            .pro
          </StyledTypography>
        </Box>
      </Link>
      {showPlayIcon && (
        <IconButton
          aria-label="dashboard"
          onClick={navigateOpen}
          size="large"
          sx={homeIconButtonSx(iconSize, darkMode)}
        >
          <HomeIcon
            sx={homeIconSx(iconSize, darkMode)}
          />
        </IconButton>
      )}
    </LogoWrapper>
  );
};

// PortalDraghandleButton - moved inside as a constant
const PortalDraghandleButton = forwardRef(({
  isOpen = false,
  onToggle = () => {},
  id = "draghandle-button",
  className = "",
  portalId = "draghandle-portal",
  zIndex = 100000,
  darkMode = false,
  ...props
}, ref) => {
  const [portalElement, setPortalElement] = useState(null);
  
  // Create portal container on mount
  useEffect(() => {
    let element = document.getElementById(portalId);
    
    if (!element) {
      element = document.createElement('div');
      element.id = portalId;
      element.style.position = 'fixed';
      element.style.top = '0';
      element.style.left = '0';
      element.style.width = '0';
      element.style.height = '0';
      element.style.zIndex = zIndex;
      document.body.appendChild(element);
    }
    
    setPortalElement(element);
    
    return () => {
      if (element && element.parentNode && element.childNodes.length <= 1) {
        document.body.removeChild(element);
      }
    };
  }, [portalId, zIndex]);
  
  const buttonComponent = (
    <IconButton
      ref={ref}
      color="primary"
      aria-label="menu"
      onClick={onToggle}
      id={id}
      className={className}
      sx={portalButtonSx(darkMode, props.style)}
      {...props}
    >
      <DragHandleIcon sx={portalDragIconSx(darkMode)} />
    </IconButton>
  );
  
  if (!portalElement) {
    return null;
  }
  
  return createPortal(buttonComponent, portalElement);
});

PortalDraghandleButton.displayName = 'PortalDraghandleButton';

const TopIconsPrivate = ({ isXs, isHomePage, useTheme: propsUseTheme, user, darkMode }) => {
  const navigate = useNavigate();
  // Remove the local darkMode from useDarkMode since we're getting it as a prop
  const { drawerOpen, toggleDrawer } = useDrawer();
  const theme = useTheme();
  const isExtraSmall = useMediaQuery(theme.breakpoints.down('sm'));
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const { t, i18n } = useTranslation();
  const queryClient = useQueryClient();
  const { refetch } = useAuth();
  
  const [userMenuAnchor, setUserMenuAnchor] = useState(null);
  const [languageMenuAnchor, setLanguageMenuAnchor] = useState(null);
  
  const [showFixedButton, setShowFixedButton] = useState(false);
  const [showIconButton, setShowIconButton] = useState(true);
  const [isLogoFixed, setIsLogoFixed] = useState(false);
  const [buttonCoords, setButtonCoords] = useState({ right: 0 });
  const [scrolled, setScrolled] = useState(false);
  
  // Define available languages
  const languages = [
    { code: 'en', label: 'English' },
    { code: 'it', label: 'Italiano' },
  ];
  
  // Get current language label
  const getCurrentLanguageLabel = () => {
    const currentLang = user?.language || i18n.language || 'en';
    const langObj = languages.find(lang => lang.code === currentLang);
    return langObj ? langObj.label.substring(0, 2).toUpperCase() : 'EN';
  };
  
  const toolbarRef = useRef(null);
  const dragHandleRef = useRef(null);
  
  const calculatePosition = () => {
    if (dragHandleRef.current) {
      const rect = dragHandleRef.current.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      const right = viewportWidth - rect.right;
      setButtonCoords({ right });
    }
  };
  
  const handleScroll = () => {
    const scrollY = window.scrollY;
    const toolbarBottom = toolbarRef.current ? toolbarRef.current.getBoundingClientRect().bottom : 0;
    
    // Set scrolled state for visual changes
    setScrolled(scrollY > 50);
    
    const nowScrolledDown = scrollY > 0 && toolbarBottom <= 0;
    
    if (nowScrolledDown) {
      setShowFixedButton(true);
      setShowIconButton(false);
      setIsLogoFixed(true);
      calculatePosition();
    } else {
      setShowFixedButton(false);
      setShowIconButton(true);
      setIsLogoFixed(false);
    }
  };
  
  useEffect(() => {
    calculatePosition();
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', calculatePosition);
    
    return () => {
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', calculatePosition);
    };
  }, []);
  
  // eslint-disable-next-line
  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const navigateOpen = (path) => {
    if (path === 'toggleDrawer') {
      toggleDrawer();
    } else {
      navigate(path);
    }
  };
  
  // Form handling for language change
  const { handleSubmit } = useForm({
    defaultValues: { language: user?.language },
  });

  const { setValue } = useForm({
    defaultValues: { language: user?.language },
  });

  const mutation = useMutation(UpdateMe, {
    onSuccess: () => queryClient.invalidateQueries(["Me"]),
  });

  // Logout handler
  const handleLogout = async () => {
    await Clear();
    await Logout();
    await refetch();
    navigate("/auth/login");
  };

  // Language change handler
  const handleLanguageChange = async (languageCode) => {
    if (!languageCode) return;
    
    try {
      await mutation.mutateAsync({ language: languageCode });
      await i18n.changeLanguage(languageCode);
      queryClient.invalidateQueries(["Me"]);
      setLanguageMenuAnchor(null);
    } catch (error) {
      console.error("Error updating language:", error);
    }
  };

  // Trial refresh handler - removed since we're using RouterLink now
  
  return (
    <>
      <StyledAppBar position="static" elevation={0} color="transparent" darkMode={darkMode} scrolled={scrolled}>
        <StyledToolbar ref={toolbarRef} darkMode={darkMode}>
          {/* Logo Component on the left */}
          <LogoComponent 
            darkMode={darkMode} 
            isHomePage={isHomePage} 
            navigateOpen={() => navigateOpen('/')}
            logoText='startersaas.pro'
            isFixed={isLogoFixed}
          />
          
          {/* DragHandle IconButton */}
          {showIconButton && (
            <IconButton 
              ref={dragHandleRef}
              color="primary"
              aria-label="menu"
              onClick={() => toggleDrawer()}
              id="draghandle"
              className="my-custom-class"
              sx={dragHandleIconButtonSx(darkMode)}
            >
              <DragHandleIcon sx={dragHandleIconSx(darkMode)} />
            </IconButton>
          )}
        </StyledToolbar>
        
        {/* Second Toolbar for buttons with modern styling */}
        <Toolbar sx={{
          ...secondToolbarSx(scrolled, darkMode),
          flexWrap: 'wrap',
          '& > *': {
            flexShrink: 0,
          }
        }}>
          {/* Home Button */}
          <ModernButton
            component={RouterLink}
            to="/dashboard"
            endIcon={<DragIndicatorIcon />}
            size="small"
            onClick={() => navigateOpen('/dashboard')}
            darkMode={darkMode}
            sx={homeButtonSx(darkMode)}
          >
            Home
          </ModernButton>
          
          {/* Language Button */}
          {user && (
            <ModernButton
              endIcon={<ExpandMoreIcon sx={{ fontSize: '0.9rem' }} />}
              size="small"
              onClick={(e) => setLanguageMenuAnchor(e.currentTarget)}
              darkMode={darkMode}
              sx={languageButtonSx(darkMode)}
            >
              {getCurrentLanguageLabel()}
            </ModernButton>
          )}
          
          {/* Account Button */}
          {user && (
            <ModernButton
              endIcon={<ExpandMoreIcon sx={{ fontSize: '0.9rem' }} />}
              size="small"
              onClick={(e) => setUserMenuAnchor(e.currentTarget)}
              darkMode={darkMode}
              sx={accountButtonSx(darkMode)}
            >
              Account
            </ModernButton>
          )}
          
          {/* FSBO Leads Button - now always visible */}
          <ModernButton
            size="small"
            onClick={() => navigateOpen('/subscriber')}
            darkMode={darkMode}
            sx={languageButtonSx(darkMode)}
          >
            FSBO Leads
          </ModernButton>

          {/* Trial Refresh Button - only for superadmin */}
          {user?.role === 'superadmin' && (
            <ModernButton
              startIcon={<RefreshIcon sx={{ fontSize: '0.9rem' }} />}
              size="small"
              onClick={() => navigateOpen('/admin/refresh')}
              darkMode={darkMode}
              sx={languageButtonSx(darkMode)}
            >
              Trial Refresh
            </ModernButton>
          )}
        </Toolbar>
      </StyledAppBar>
      
      {/* Language Menu with modern styling */}
      {user && (
        <Menu 
          anchorEl={languageMenuAnchor} 
          open={Boolean(languageMenuAnchor)} 
          onClose={() => setLanguageMenuAnchor(null)}
          sx={menuPaperSx(darkMode)}
        >
          {languages.map((lang) => (
            <MenuItem 
              key={lang.code}
              onClick={() => handleLanguageChange(lang.code)}
              selected={user?.language === lang.code}
              sx={menuItemSx(darkMode, user?.language === lang.code)}
            >
              {lang.label}
            </MenuItem>
          ))}
        </Menu>
      )}
      
      {/* User Menu with modern styling */}
      {user && (
        <Menu 
          anchorEl={userMenuAnchor} 
          open={Boolean(userMenuAnchor)} 
          onClose={() => setUserMenuAnchor(null)}
          sx={menuPaperSx(darkMode)}
        >
          <MenuItem disabled sx={disabledMenuItemSx(darkMode)}>
            {user.email}
          </MenuItem>
          <MenuItem 
            component={RouterLink} 
            to="/user/edit" 
            sx={menuItemSx(darkMode)}
          >
            {t("privateLayout.manageUser")}
          </MenuItem>
          {(user.role === "admin" || user.role === "superadmin") && (
            <>
              <MenuItem 
                component={RouterLink} 
                to="/account/edit" 
                sx={menuItemSx(darkMode)}
              >
                {t("privateLayout.managePayment")}
              </MenuItem>
              <MenuItem 
                component={RouterLink} 
                to="/plan" 
                sx={menuItemSx(darkMode)}
              >
                {t("privateLayout.managePlan")}
              </MenuItem>
            </>
          )}
          <MenuItem onClick={handleLogout} sx={menuItemSx(darkMode)}>
            {t("privateLayout.logout")}
          </MenuItem>
        </Menu>
      )}
      
      {/* Portal Button that appears when scrolled down (outside toolbar) */}
      {!showIconButton && showFixedButton && (
        <PortalDraghandleButton 
          isOpen={drawerOpen}
          onToggle={() => toggleDrawer()}
          id="draghandle-fixed" 
          className="my-custom-class"
          darkMode={darkMode}
          style={{
            position: "fixed",
            top: 10,
            right: `${buttonCoords.right}px`,
            transform: "translateZ(0)",
            willChange: "transform",
            zIndex: 1300,
          }}
        />
      )}
    </>
  );
};

export default TopIconsPrivate;